#include <iostream>
#include <set>
using namespace std;


struct num{
	int father;
	set<int> s;
};


num get(int x,num f[]){
	if(f[x].father == x)
		return f[x];
	return f[x]=get(f[x].father,f);
}


void cac(){
	int n;
	cin>>n;
	num f[n];
	int rk[n];
	for(int i=0;i<n;i++){
		f[i].father = i;
		rk[i] = 1;
	}
	bool out=true;
	for(int i=0;i<n;i++){
		int x,y,z;
		cin>>x>>y>>z;
		x--;
		y--;
		if(!out)
			continue;
		num fx,fy;
		fx = get(x,f);
		fy = get(y,f);
		if(z == 1){
			if(fx.father == fy.father)
				continue;
			if(fx.s.size() < fy.s.size()){
				for(auto it=fx.s.begin();it!=fx.s.end();it++) {
					num l;
					l = get(*it,f);
					fx.s.erase(*it);
					if(l.father == fy.father){
						out = false;
						break;
					}
					fx.s.insert(l.father);
				   }
			}
			else{
				for(auto it=fy.s.begin();it!=fy.s.end();it++) {
					num l;
					l = get(*it,f);
					fy.s.erase(*it);
					if(l.father == fy.father){
						out = false;
						break;
					}
					fy.s.insert(l.father);
				}
			}
			
			if(!out)
				continue;
			
			if(rk[fx.father] == rk[fy.father]){
				rk[fx.father]++;
				f[fy.father].father = fx.father;
				f[fx.father].s.insert(f[fy.father].s.begin(),f[fy.father].s.end());
			}
			else if(rk[fx.father] < rk[fy.father]){
				f[fx.father].father = fy.father;
				f[fy.father].s.insert(f[fx.father].s.begin(),f[fx.father].s.end());
			}
			else{
				f[fy.father].father = fx.father;
				f[fx.father].s.insert(f[fy.father].s.begin(),f[fy.father].s.end());
			}
		}
		else{
			if(fx.father == fy.father){
				out = false;
			}
			f[fx.father].s.insert(fy.father);
			f[fy.father].s.insert(fx.father);
		}
	}
	if(out)
		cout<<"YES"<<endl;
	else
		cout<<"NO"<<endl;
	return;
}


int main(){
	int t;
	cin>>t;
	for(int k=0;k<t;k++){
		cac();
	}
	return 0;
}
